import { useNetworkStore } from '@/common/hox/networkStore'
import appConfig from '@/utils/appConfig'
import { Image } from '@tarojs/components'
import Taro, { useDidHide, useDidShow, useUnload } from '@tarojs/taro'
import React, { useEffect, useRef, useState } from 'react'
import styles from './index.module.less'
import noNetworkPic from './noNetwork'

export type PageRefType = {
  didShow?: () => void,
  didHide?: () => void,
  unload?: () => void,
}
export type PagePropsType = {
  isPageShow: boolean,
}

export default function withPageContainer(Component: React.ForwardRefRenderFunction<PageRefType, PagePropsType>) {
  const ComponentWithRef = React.forwardRef(Component)
  return (_props: any) => { 
    const { networkAvailable, reCheckNetwork, pageDidShow, pageDidHide, isTimeout, resetRequestTimeout } = useNetworkStore()
    const pageRef = useRef<PageRefType>(null)
    const [isPageShow, setIsPageShow] = useState(false)
    
    useDidShow(() => {
      pageDidShow()
      setIsPageShow(true)
      pageRef.current?.didShow?.()
    })
    useDidHide(() => { 
      pageDidHide()
      setIsPageShow(false)
      pageRef.current?.didHide?.()
    })
    useUnload(() => { 
      pageRef.current?.unload?.()
    })

    useEffect(() => { 
      if (!networkAvailable || isTimeout) Taro.hideLoading()
    }, [networkAvailable, isTimeout])

    // 无网判断 开发测试微信开发者工具存在问题，这里添加开启配置项 appConfig.networkAvailableCheck
    if (appConfig.networkAvailableCheck !== false && !networkAvailable) { 
      return (
        <div className={styles.noNetwork}>
          <Image className={styles.pic} src={noNetworkPic}></Image>
          <div className={styles.title}>网络未连接</div>
          <div className={styles.dec}>请检查网络设置或刷新页面</div>
          <div className={styles.btn} onClick={reCheckNetwork}>刷新</div>
        </div>
      )
    }

    if (isTimeout) { 
      return (
        <div className={styles.noNetwork}>
          <Image className={styles.pic} src={noNetworkPic}></Image>
          <div className={styles.title}>超时未响应</div>
          <div className={styles.dec}>请检查网络设置或刷新页面</div>
          <div className={styles.btn} onClick={resetRequestTimeout}>刷新</div>
        </div>
      )
    }
    
    return <ComponentWithRef isPageShow={isPageShow} ref={pageRef} />
  }
}